import { loginAccount, loginPhone, phoneCode,picCode,logoutAccount,getInfo } from '@/api/login'
import {getUserToken}  from "@/api/statistics";
import { getToken, setToken, removeToken ,getUuid,setUuid,removeFooter,setLoginInfo,getLoginInfo,removeLoginInfo,
  setName,getName,removeName,getlocalStorage,setlocalStorage
} from '@/utils/auth'
import {constantRoutes, resetRouter} from '@/router'
import {encryptByDESModeCBCUtf8to64} from "@/utils";
import CryptoJS from "crypto-js";
import {Message} from "element-ui";
import {getMeun} from "@/api";
import store from "@/store/index";
import {getAnonymousList,getNoAnonymousList} from "@/api/index";
const getDefaultState = () => {
  return {
    token: getToken() || "", //正常登录使用的token
    tokenId: sessionStorage.getItem("tokenId") || "", //从管理平台跳转使用的tokenId
    name: getLoginInfo("name") || "", //用户的名字
    headerimg: getLoginInfo("headerimg") || "", //用户头像
    sex: getLoginInfo("sex") || "",
    avatar: "",
    introduction: "",
    roles: [],
    permissions: [],
    permisaction: [],
    uuid: getUuid(),
    timestamp: "",
    studyTime: getLoginInfo("studyTime"),
    showLogin: false, //直播登录的标识

    toAnonymousRead: JSON.parse(getlocalStorage('toAnonymousRead')) || false,//非匿名必读通知公告
    toNoAnonymousRead: JSON.parse(getlocalStorage('toRead')) || false,//匿名必读通知公告
    readTime: JSON.parse(getlocalStorage('readTime')) || 0,
    noticeList: JSON.parse(getlocalStorage('noticeList')) || []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKENID: (state, tokenId) => {
    state.tokenId = tokenId;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_PERMISSIONS: (state, permisaction) => {
    state.permisaction = permisaction;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_UUID: (state, uuid) => {
    state.uuid = uuid;
  },
  SET_HEADERIMG(state, headerimg) {
    state.headerimg = headerimg;
  },
  SET_SEX(state, sex) {
    state.sex = sex;
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_SHOWLOGIN(state, showLogin) {
    state.showLogin = showLogin;
  },
  SET_READTIME(state, readTime) {
    state.readTime = readTime
    setlocalStorage('readTime', readTime)
  },
  SET_NOTICELIST(state, noticeList) {
    state.noticeList = noticeList
  }

}

const actions = {
  getNotice({ commit },path) {
    console.log(path)
    var toNoAnonymousRead = state.toNoAnonymousRead
    var toAnonymousRead =state.toAnonymousRead
    if (getToken() && !toNoAnonymousRead) {
      var data = {
        position: path
      }
      getNoAnonymousList(data).then((response) => {
        commit('SET_NOTICELIST', response.data)
        setlocalStorage('noticeList', JSON.stringify(response.data))
      })
        .catch((err) => {
          Message.error(err.message)
        })
    } else if (!toAnonymousRead) {
      var data = {
        position: path
      }
      getAnonymousList(data).then((response) => {
        commit('SET_NOTICELIST', response.data)
        setlocalStorage('noticeList', JSON.stringify(response.data))
      })
      .catch((err) => {
        Message.error(err.message)

      })
    }
    var readTime = state.readTime
    if (readTime) {
      var timer = setInterval(() => {
        readTime--
        commit('SET_READTIME', readTime)
        if (readTime <= 0) {
          clearInterval(timer)
          removelocalStorage('toNoAnonymousRead')
          removelocalStorage('toAnonymousRead')
          removelocalStorage('readTime')
        }
      }, 1000)
    }
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password, picCode } = userInfo;
    var timestamp = new Date().getTime();
    var authKey =
      username +
      "|" +
      password +
      "|" +
      picCode +
      "|" +
      state.uuid +
      "|" +
      timestamp;
    authKey = encryptByDESModeCBCUtf8to64(
      "xzxzxzxz",
      authKey.toString(),
      CryptoJS
    );
    authKey = encodeURIComponent(authKey);
    return new Promise((resolve, reject) => {
      loginAccount({ authKey, timestamp: timestamp.toString() })
        .then((response) => {
          const { data } = response;
          commit("SET_TOKEN", data);
          store.dispatch('user/getInfo');
          setToken(data);
          resolve(data);
        })
        .catch((error) => {
          Message.error(error.message);
          reject(error);
        });
    });
  },

  setUuid({ commit }, uuid) {
    commit("SET_UUID", uuid);
    setUuid(uuid);
  },
  getTokenId({ commit }, authKey) {
    return new Promise((resolve, reject) => {
      getUserToken(authKey)
        .then((response) => {
          const { data } = response;
          if (typeof data === "string") {
            commit("SET_TOKENID", data);
            sessionStorage.setItem("tokenId", data);
            resolve();
          } else {
            reject(response);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const { data } = response;
          const { name, headerimg, sex } = data;
          commit("SET_NAME", name);
          commit("SET_HEADERIMG", headerimg);
          commit("SET_SEX", sex);
          setName(name);
          for (var key in data) {
            setLoginInfo(key, data[key]);
          }
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logoutAccount()
        .then((response) => {
          if (response.code == 1200) {
            removeToken(); // must remove  token  first
            removeName(); // must remove  name
            removeLoginInfo("name");
            removeLoginInfo("headerimg");
            removeLoginInfo("sex");
            removeFooter();
            resetRouter();
            commit("RESET_STATE");
            resolve();
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      removeName(); // must remove  name
      removeLoginInfo("name");
      removeLoginInfo("headerimg");
      removeLoginInfo("sex");
      removeFooter();
      resetRouter();
      commit("RESET_STATE");
      resolve();
    });
  },
  resetTokenId({ commit }) {
    return new Promise((resolve) => {
      sessionStorage.removeItem("tokenId");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

